package StringStudy;

/**
 * 需求:定义一个int数组,按照指定的格式拼成字符串返回{1, 2, 3}-->[1,2,3]
 */
public class StringLearn3 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        System.out.println("arrTostr() = " + arrTostr(arr));
        System.out.println("reverse(\"adadadadad\") = " + reverse("adadadadad"));
        System.out.println("reverse1(\"dadawdadawda\") = " + reverse1("dadawdadawda"));
        StringLearn3 stringLearn3 = new StringLearn3();
        String s = stringLearn3.arrToString(arr);
        System.out.println("s = " + s);
    }

    //用stringbuilder转换数组到字符串
    public String arrToString(int[] arr) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                stringBuilder.append(arr[i]);
            } else {
                stringBuilder.append(arr[i]).append(",");
            }
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }

    /**
     * 数组转成指定格式的字符串
     *
     * @param arr
     * @return
     */
    public static String arrTostr(int[] arr) {
        String str = "[";
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                str += arr[i];
            } else {
                str += arr[i] + ",";
            }
        }
        str += "]";
        return str;
    }

    /**
     * 字符串逆置1
     *
     * @param str
     * @return
     */
    public static String reverse(String str) {//axyz;
        //zy
        String res = "";
        for (int i = 0; i < str.length(); i++) {//4
            res += str.charAt(str.length() - i - 1);
        }
        return res;
    }

    /**
     * 字符串逆置2
     *
     * @param str
     * @return
     */
    public static String reverse1(String str) {
        String res = "";
        for (int i = str.length() - 1; i >= 0; i--) {
            res += str.charAt(i);
        }
        return res;
    }
}
